// pages/addAddress/addAddress.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    checked: false,
    phone: '',
    errorMessage: '',
    address: '',
    name: '',
    detailAddress: '',
    isEdit: false,
    addressId: ''
  },

  // 返回
  onClickLeft() {
    wx.navigateBack({
      delta: 1
    });
  },

  onChange({ detail }) {
    this.setData({
      checked: detail
    });
  },

  // 定位
  positioning() {
    const that = this;
    wx.chooseLocation({
      success(res) {
        if (res.address) {
          that.setData({
            address: res.address + ' ' + res.name
          });
        }
      },
      fail(err) {
        console.error('选择位置失败:', err);
        wx.showToast({
          title: '获取位置失败',
          icon: 'none'
        });
      }
    });
  },

  // 验证手机号输入
  checkPhoneInput(e) {
    const value = e.detail.value;
    this.setData({
      phone: value
    });
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(value)) {
      this.setData({
        errorMessage: '请输入正确的手机号'
      });
    } else {
      this.setData({
        errorMessage: ''
      });
    }
  },

  // 新增输入绑定事件（收货人、详细地址）
  handleInput(e) {
    const field = e.currentTarget.dataset.field;
    this.setData({
      [field]: e.detail.value
    });
  },

  // 保存地址到云数据库
  saveAddress: async function () {
    // 数据验证
    if (!this.data.name) {
      wx.showToast({
        title: '请填写收货人',
        icon: 'none'
      });
      return;
    }
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(this.data.phone)) {
      wx.showToast({
        title: '手机号不合法',
        icon: 'none'
      });
      return;
    }
    if (!this.data.address) {
      wx.showToast({
        title: '请选择所在地区',
        icon: 'none'
      });
      return;
    }
    if (!this.data.detailAddress) {
      wx.showToast({
        title: '请填写详细地址',
        icon: 'none'
      });
      return;
    }

    const db = wx.cloud.database();
    const updateDefaultAddress = async () => {
      if (this.data.checked) {
        await db.collection('addresses').where({
          isDefault: true
        }).update({
          data: {
            isDefault: false
          }
        });
      }
    };

    // 检查地址是否存在的函数
    // 获取当前用户的ID
const userId = wx.getStorageSync('userId');

    const checkAddressExists = async () => {
      const existingAddress = await db.collection('addresses').where({
        name: this.data.name,
        phone: this.data.phone,
        address: this.data.address,
        detailAddress: this.data.detailAddress,
        userId: userId, // 添加用户ID条件
        _id: this.data.isEdit ? { $ne: this.data.addressId } : null
      }).get();

      return existingAddress.data.length > 0;
    };

    // 保存或更新地址的主函数
    const saveOrUpdate = async () => {
      await updateDefaultAddress();
      const exists = await checkAddressExists();
      if (exists) {
        wx.showToast({
          title: '该地址信息已存在',
          icon: 'none'
        });
        setTimeout(() => wx.navigateBack(), 1500);
        return;
      }

      const data = {
        name: this.data.name,
        phone: this.data.phone,
        address: this.data.address,
        detailAddress: this.data.detailAddress,
        isDefault: this.data.checked,
        userId: userId, // 添加用户ID字段
        createTime: this.data.isEdit ? undefined : db.serverDate()
      };

      if (this.data.isEdit) {
        await db.collection('addresses').doc(this.data.addressId).update({
          data
        });
      } else {
        await db.collection('addresses').add({
          data
        });
      }
    };

    // 调用主函数并处理结果
    saveOrUpdate()
      .then(() => {
        wx.showToast({
          title: '操作成功'
        });
        setTimeout(() => wx.navigateBack(), 1500);
      })
      .catch(err => {
        console.error('操作失败:', err);
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        });
      });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.address) {
      try {
        const decodedAddress = decodeURIComponent(options.address);
        const address = JSON.parse(decodedAddress);
        this.setData({
          isEdit: true,
          addressId: address._id,
          name: address.name,
          phone: address.phone,
          address: address.address,
          detailAddress: address.detailAddress,
          checked: address.isDefault
        });
      } catch (err) {
        console.error('参数解析失败:', err);
        wx.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      }
    }
  }
});